package com.mazewei.dev.controller;

import com.mazewei.dev.service.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传控制器
 * 处理Excel文件上传和数据转换
 */
@RestController
@RequestMapping("/upload")
public class FileUploadController {

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 统一处理Excel文件上传和转换（支持单工作表和多工作表）
     * @param file Excel文件
     * @param startCol 起始列
     * @param endCol 结束列
     * @param startRow 起始行
     * @param endRow 结束行
     * @param sheetNames 工作表名称（可选，多个用逗号分隔）
     * @param schoolSection 学部选择（primary=小学部，middle=初中部）
     * @return 处理结果
     */
    @PostMapping("/process")
    public ResponseEntity<Map<String, Object>> handleFileUpload(
            @RequestParam("file") MultipartFile file,
            @RequestParam("startCol") String startCol,
            @RequestParam("endCol") String endCol,
            @RequestParam("startRow") int startRow,
            @RequestParam("endRow") int endRow,
            @RequestParam(value = "sheetNames", required = false) String sheetNames,
            @RequestParam(value = "schoolSection", defaultValue = "primary") String schoolSection,
            @RequestParam(value = "dataMode", defaultValue = "strict") String dataMode) {
        
        try {
            // 验证文件
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "请选择要上传的文件"
                ));
            }
            
            // 验证文件类型
            String fileName = file.getOriginalFilename();
            if (fileName == null) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "文件名无效"
                ));
            }
            
            String lowerFileName = fileName.toLowerCase();
            if (!lowerFileName.endsWith(".xls") && 
                !lowerFileName.endsWith(".xlsx") && 
                !lowerFileName.endsWith(".csv")) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "只支持 .xls、.xlsx 和 .csv 格式的文件"
                ));
            }
            
            // 验证文件大小 (10MB)
            if (file.getSize() > 10 * 1024 * 1024) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "文件大小不能超过 10MB"
                ));
            }
            
            // 验证参数
            if (startCol == null || startCol.trim().isEmpty() ||
                endCol == null || endCol.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "起始列和结束列不能为空"
                ));
            }
            
            if (startRow <= 0 || endRow <= 0 || startRow > endRow) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "行号参数无效"
                ));
            }
            
            Map<String, Object> result;
            
            // 判断是单工作表还是多工作表处理
            if (sheetNames != null && !sheetNames.trim().isEmpty()) {
                // 多工作表处理
                String[] sheetNameArray = sheetNames.split(",");
                for (int i = 0; i < sheetNameArray.length; i++) {
                    sheetNameArray[i] = sheetNameArray[i].trim();
                }
                result = fileUploadService.processMultiSheetExcel(
                    file, sheetNameArray, startCol, endCol, startRow, endRow, schoolSection, dataMode);
            } else {
                // 单工作表处理
                result = fileUploadService.processExcel(
                    file, startCol, endCol, startRow, endRow, schoolSection, dataMode);
            }
            
            return ResponseEntity.ok(result);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", e.getMessage()
            ));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of(
                "success", false,
                "message", "处理过程中发生错误: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取文件上传状态
     * @return 状态信息
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getUploadStatus() {
        Map<String, Object> status = fileUploadService.getUploadStatus();
        return ResponseEntity.ok(status);
    }

    /**
     * 清理旧文件
     * @param keepDays 保留天数，默认7天
     * @return 清理结果
     */
    @DeleteMapping("/cleanup")
    public ResponseEntity<Map<String, Object>> cleanupFiles(
            @RequestParam(value = "keepDays", defaultValue = "7") int keepDays) {
        Map<String, Object> result = fileUploadService.cleanupFiles(keepDays);
        return ResponseEntity.ok(result);
    }

    /**
     * 预览Excel文件内容
     * @param file 文件路径参数
     * @return 预览数据
     */
    @GetMapping("/preview")
    public ResponseEntity<Map<String, Object>> previewExcelFile(
            @RequestParam("file") String file) {
        try {
            Map<String, Object> result = fileUploadService.previewExcelFile(file);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of(
                "success", false,
                "message", "预览文件时发生错误: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取上传帮助信息
     * @return 帮助信息
     */
    @PostMapping("/help")
    public ResponseEntity<Map<String, Object>> getUploadHelp() {
        Map<String, Object> help = new HashMap<>();
        help.put("success", true);
        help.put("message", "文件上传功能帮助");
        help.put("supportedFormats", ".xls (Excel 97-2003)");
        help.put("maxFileSize", "10MB");
        help.put("requiredParameters", Map.of(
            "file", "Excel文件",
            "startCol", "起始列 (如: C)",
            "endCol", "结束列 (如: L)",
            "startRow", "起始行 (数字)",
            "endRow", "结束行 (数字)",
            "sheetNames", "工作表名称 (可选，多个用逗号分隔)"
        ));
        help.put("conversionRule", "编码@名称 -> 编码-名称");
        help.put("apiEndpoints", Map.of(
            "unified", "/upload/process - 统一处理接口（推荐）",
            "single", "/upload/template1 - 单工作表处理（兼容）",
            "multi", "/upload/multisheet - 多工作表处理（兼容）"
        ));
        help.put("supportedFormats", Map.of(
            "teacher", "教师格式: 2024206@丁清 -> 2024206-丁清",
            "class", "班级格式: 2024001@一年1班 -> 2024001-一年1班",
            "course", "课程格式: pmal01@数学（一上） -> pmal01-数学（一上）"
        ));
        
        return ResponseEntity.ok(help);
    }

    /**
     * 兼容性接口：单工作表处理
     * @deprecated 请使用 /process 接口
     */
    @PostMapping("/template1")
    public ResponseEntity<Map<String, Object>> handleSingleSheetUpload(
            @RequestParam("file") MultipartFile file,
            @RequestParam("startCol") String startCol,
            @RequestParam("endCol") String endCol,
            @RequestParam("startRow") int startRow,
            @RequestParam("endRow") int endRow) {
        
        return handleFileUpload(file, startCol, endCol, startRow, endRow, null, "primary", "strict");
    }
    
    /**
     * 兼容性接口：多工作表处理
     * @deprecated 请使用 /process 接口
     */
    @PostMapping("/multisheet")
    public ResponseEntity<Map<String, Object>> handleMultiSheetUpload(
            @RequestParam("file") MultipartFile file,
            @RequestParam("sheetNames") String sheetNames,
            @RequestParam("startCol") String startCol,
            @RequestParam("endCol") String endCol,
            @RequestParam("startRow") int startRow,
            @RequestParam("endRow") int endRow) {
        
        return handleFileUpload(file, startCol, endCol, startRow, endRow, sheetNames, "primary", "strict");
    }
}